package user.zc.controller.impl;

import user.zc.controller.IConnect;
import user.zc.controller.ISystemConfig;
import user.zc.controller.ISystemTemplate;

import javax.swing.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class GuiProxyFactory {

    static class GuiProxy<T> implements InvocationHandler {

        private T target ;
        public GuiProxy(T target){
            this.target = target;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                return method.invoke(target, args);
            } catch (InvocationTargetException e) {
                JOptionPane.showMessageDialog(null,
                        e.getTargetException().getMessage(), "异常信息", JOptionPane.ERROR_MESSAGE);
                throw new Throwable(e.getMessage());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,
                        e.getMessage(), "异常信息", JOptionPane.ERROR_MESSAGE);
                throw new Throwable(e.getMessage());
            }
        }
    }

    public static <T,R extends T> T getProxy(InvocationHandler inter, R target){
        return  (T)Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                inter);
    }

    public static IConnect getConnectionProxy(){
        ConnectCollector connectCollector = new ConnectCollector();
        return  getProxy(new GuiProxy(connectCollector),connectCollector);
    }

    public static ISystemConfig getStemConfigProxy(){
        SystemConfigController systemConfigController = new SystemConfigController();
        return  getProxy(new GuiProxy(systemConfigController),systemConfigController);
    }

    public static ISystemTemplate getSysteTemplateConfigProxy(){
        SystemTemplateController systemTemplateController = new SystemTemplateController();
        return getProxy(new GuiProxy(systemTemplateController), systemTemplateController);
    }

}
